<template>
	<view>
		<view v-if="login">
			<van-search :value="search" @change="onChangeSearch" placeholder="请输入搜索关键词" @search="onSearch(search)"></van-search>
			<van-sticky>
				<view class="filter">
					<view @click="onChange(0)" :style="'color:'+(choose==0?'#11b24e':'#555555')+';'">销量优先</view>
					<view @click="onChange(1)" :style="'color:'+(choose==1?'#11b24e':'#555555')+';'">评分优先</view>
				</view>
			</van-sticky>
			<view v-for="(item,index) in shop" :key="item.shopId">
				<myShop :shopId="item.shopId" :shopName="item.shopName" :image="item.image" :status="item.status" :totCnt="item.totCnt" :score="item.score" :discount="item.discount"></myShop>
			</view>
			<view class="safeView"></view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				search:'',
				choose:0,
				shop:[],
				login:false
			}
		},
		onLoad() {
			const that=this;
			wx.showNavigationBarLoading();
			wx.login({
				success:function(res){
					wx.request({
						url:that.myConfig.apiUrl+'/login.php',
						method:'POST',
						data:{
							code:res.code
						},
						success:function(ress){
							wx.hideNavigationBarLoading();
							console.log('login',ress);
							that.myConfig.openId=ress.data.openId;
							that.login=true;
						},
						fail:function(){
							wx.hideNavigationBarLoading();
							that.myConfig.err();
						}
					});
				},
				fail:function(){
					wx.hideNavigationBarLoading();
					that.myConfig.err();
				}
			});
		},
		onShow(){
			const that=this;
			that.onSearch('');
		},
		methods: {
			//搜索
			onSearch(string){
				const that=this;
				wx.showNavigationBarLoading();
				wx.request({
					url:that.myConfig.apiUrl+'/getShopList.php',
					data:{
						shopName:string
					},
					success:function(res){
						wx.hideNavigationBarLoading();
						console.log('getShopList',res);
						that.shop=res.data.shop;
						that.mySort(0);
					},
					fail:function(){
						wx.hideNavigationBarLoading();
						that.myConfig.err();
					}
				});
			},
			//排序
			mySort(flag){
				const that=this;
				const compare= function(proper){
					return function(x, y){
						if(x.status&&y.status)
							return y[proper] - x[proper];
						else if(x.status==false)
							return 1;
						else
							return -1;
					}
				}
				if(flag==0)
					that.shop.sort(compare('totCnt'));
				else
					that.shop.sort(compare('score'));
				let tmp=[];
				tmp=that.shop;
				that.shop=tmp;
			},
			//排序方式
			onChange(flag){
				const that=this;
				if(that.choose!=flag){
					that.mySort(flag);
					that.choose=flag;
				}
			},
			//v-model
			onChangeSearch(value){
				this.search=value.detail;
			},
		}
	}
</script>

<style scoped>
	.filter{
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding: 25rpx 0rpx;
		font-weight: 800;
		background-color: #ffffff;
		color: #969799;
	}
</style>
